from neo4j import GraphDatabase
# 定义一个函数来创建节点和关系
def create_nodes_and_relationship(tx, node_1, node_2, edge):
    # 创建节点
    tx.run("MERGE (n1:Node {name: $node_1})", node_1=node_1)
    tx.run("MERGE (n2:Node {name: $node_2})", node_2=node_2)
    # 创建关系
    tx.run("MATCH (n1:Node {name: $node_1}), (n2:Node {name: $node_2}) "
           "MERGE (n1)-[:RELATIONSHIP {description: $edge}]-(n2)",
           node_1=node_1, node_2=node_2, edge=edge)

# 遍历 concept_list 并将数据存入数据库
def generate_graph(concept_list)->list:
    # Neo4j 数据库连接信息
    uri = "bolt://localhost:7687"
    user = "neo4j"
    password = "13579Fsz"

    # 连接到 Neo4j 数据库
    driver = GraphDatabase.driver(uri, auth=(user, password))
    with driver.session() as session:
        # 先删除所有节点和关系
        session.run("MATCH (n) DETACH DELETE n")
        for item in concept_list:
            node_1 = item['node_1']
            node_2 = item['node_2']
            edge = item['edge']
            session.execute_write(create_nodes_and_relationship, node_1, node_2, edge)
    # 关闭数据库连接
    driver.close()
